"""
数据校验模块
"""
import pandas as pd
from loguru import logger
from datetime import datetime

class DataValidator:
    """股票数据校验器"""
    
    @staticmethod
    def validate_stock_data(data: pd.DataFrame, stock_code: str, start_date: str, end_date: str):
        """执行完整的数据校验流程"""
        logger.info(f"开始校验{stock_code}数据")
        
        # 基础校验
        DataValidator._check_empty(data)
        DataValidator._check_date_range(data, start_date, end_date)
        
        # 数值校验
        DataValidator._check_positive_values(data, ['开盘', '收盘', '最高', '最低', '成交量'])
        DataValidator._check_price_consistency(data)
        
        logger.success(f"{stock_code}数据校验通过")
    
    @staticmethod
    def _check_empty(data):
        """检查数据是否为空"""
        if data.empty:
            raise ValueError("获取到的数据为空")
            
    @staticmethod
    def _check_date_range(data, start_date, end_date):
        """检查日期范围完整性"""
        start_dt = datetime.strptime(start_date, "%Y%m%d")
        end_dt = datetime.strptime(end_date, "%Y%m%d")
        date_range = pd.date_range(start=start_dt, end=end_dt)
        
        missing_dates = date_range.difference(data['日期'])
        if not missing_dates.empty:
            logger.warning(f"数据缺失以下日期：{missing_dates.strftime('%Y%m%d').tolist()}")

    @staticmethod
    def _check_positive_values(data, columns):
        """检查关键字段是否为正值"""
        for col in columns:
            if (data[col] <= 0).any():
                raise ValueError(f"{col}包含非正值")

    @staticmethod
    def _check_price_consistency(data):
        """检查价格一致性：最高 >= 收盘 >= 最低"""
        if not (data['最高'] >= data['收盘']).all() or not (data['收盘'] >= data['最低']).all():
            raise ValueError("价格数据存在矛盾")